// 省市区数据
let regionData = cities;

let selectedProvince = null;
let selectedCity = null;
let selectedDistrict = null;

let activeType = '';
let lastScrollTop = 0;
let lock = false;
let lockTime = 50;

$(document).ready(function() {
	const selectBtn = document.getElementById('selectBtn');
	const cityPicker = document.getElementById('cityPicker');
	const pickerMask = document.getElementById('pickerMask');
	const pickerContainer = document.getElementById('pickerContainer');
	const pickerClose = document.getElementById('pickerClose');
	const pickerContent = document.getElementById('pickerContent');
	// 事件监听
	selectBtn.addEventListener('click', showPicker);
	pickerClose.addEventListener('click', hidePicker);
	pickerMask.addEventListener('click', hidePicker);

});

// 初始化选择器
function initPicker() {
	pickerContent.innerHTML = '';

	// 省份列
	const provinceCol = document.createElement('div');
	provinceCol.className = 'picker-column';
	provinceCol.id = 'provinceCol';
	provinceCol.addEventListener('touchstart', () => {
		// console.log(`#provinceCol touchstart`);
		lastScrollTop = $("#provinceCol").scrollTop();
	});
	provinceCol.addEventListener('scroll', (e) => {
		// console.log(`#provinceCol scroll `);
		const offsetTop = $("#provinceCol").scrollTop();
		const delta = offsetTop - lastScrollTop; // 滚动方向
		// console.log(`#provinceCol delta = ${offsetTop} - ${lastScrollTop} = ${delta}`);
		if (activeType != 'isUserClick' && !lock) {
			lock = true;
			setTimeout(() => lock = false, lockTime);
			let offsetIndex = null;
			if (delta >= 1) offsetIndex = Math.floor((offsetTop + 10) / 60); // 正向滚动
			if (delta <= -1) offsetIndex = Math.floor((offsetTop - 10) / 60) + 1; // 反向滚动
			// console.log(`#provinceCol offsetIndex => ${offsetIndex}`);
			if (offsetIndex >= 0) {
				const offsetProvince = regionData[offsetIndex];
				const offsetId = `P_${offsetProvince.code}`;
				if (
					selectedProvince &&
					offsetProvince.province != selectedProvince.province &&
					offsetProvince.code != selectedProvince.code
				) {
					selectedProvince = offsetProvince;
					activeProvinceItem(selectedProvince, 'isScroll');
				}
			}
		}
		setTimeout(() => lastScrollTop = offsetTop);
	}, {
		passive: true
	});

	pickerContent.appendChild(provinceCol);

	// 城市列
	const cityCol = document.createElement('div');
	cityCol.className = 'picker-column';
	cityCol.id = 'cityCol';
	cityCol.addEventListener('touchstart', () => {
		// console.log(`#cityCol touchstart`);
		lastScrollTop = $("#cityCol").scrollTop();
	});
	cityCol.addEventListener('scroll', () => {
		// console.log(`#cityCol activeType `);
		const offsetTop = $("#cityCol").scrollTop();
		const delta = offsetTop - lastScrollTop;
		// console.log(`#cityCol delta = ${offsetTop} - ${lastScrollTop} = ${delta}`);
		if (activeType != 'isUserClick' && !lock) {
			lock = true;
			setTimeout(() => lock = false, lockTime);
			let offsetIndex = null;
			if (delta >= 1) offsetIndex = Math.floor((offsetTop + 10) / 60); // 正向滚动
			if (delta <= -1) offsetIndex = Math.floor((offsetTop - 10) / 60) + 1; // 反向滚动
			// console.log(`#cityCol offsetIndex => ${offsetIndex}`);
			if (offsetIndex >= 0) {
				const offsetCity = selectedProvince.cities[offsetIndex];
				const offsetId = `C_${offsetCity.code}`;
				if (
					selectedCity &&
					offsetCity.city != selectedCity.city &&
					offsetCity.code != selectedCity.code
				) {
					selectedCity = offsetCity;
					activeCityItem(selectedCity, 'isScroll');
				}
			}
		}
		setTimeout(() => lastScrollTop = offsetTop);
	}, {
		passive: true
	});

	pickerContent.appendChild(cityCol);

	// 区县列
	const districtCol = document.createElement('div');
	districtCol.className = 'picker-column';
	districtCol.id = 'districtCol';
	districtCol.addEventListener('touchstart', () => {
		// console.log(`#districtCol touchstart`);
		lastScrollTop = $("#districtCol").scrollTop();
	});
	districtCol.addEventListener('scroll', () => {
		// console.log(`#districtCol activeType`);
		const offsetTop = $("#districtCol").scrollTop();
		const delta = offsetTop - lastScrollTop;
		// console.log(`#districtCol delta = ${offsetTop} - ${lastScrollTop} = ${delta}`);
		if (activeType != 'isUserClick' && !lock) {
			lock = true;
			setTimeout(() => lock = false, lockTime);
			let offsetIndex = null;
			if (delta >= 1) offsetIndex = Math.floor((offsetTop + 10) / 60); // 正向滚动
			if (delta <= -1) offsetIndex = Math.floor((offsetTop - 10) / 60) + 1; // 反向滚动
			// console.log(`#districtCol offsetIndex => ${offsetIndex}`);
			if (offsetIndex >= 0) {
				const offsetDistrict = selectedCity.areas[offsetIndex];
				const offsetId = `D_${offsetDistrict.code}`;
				if (
					selectedDistrict &&
					offsetDistrict.area != selectedDistrict.area &&
					offsetDistrict.code != selectedDistrict.code
				) {
					selectedDistrict = offsetDistrict;
					activeDistrictItem(selectedDistrict, 'isScroll');
				}
			}
		}
		setTimeout(() => lastScrollTop = offsetTop);
	}, {
		passive: true
	});

	pickerContent.appendChild(districtCol);

	// 加载省份数据
	loadProvinces();
	// loadCities(regionData[0]);
	// loadDistricts(regionData[0].cities[0]);
}

// 加载省份数据
function loadProvinces() {
	const provinceCol = document.getElementById('provinceCol');
	provinceCol.innerHTML = '';

	regionData.forEach((province, index) => {
		const item = document.createElement('div');
		item.className = 'picker-item';
		item.dataset.index = index;
		item.dataset.code = province.code;
		item.textContent = province.province;
		item.id = `P_${province.code}`;
		item.addEventListener('click', () => {
			activeProvinceItem(province, 'isUserClick');
		});
		provinceCol.appendChild(item);
	});

	if (
		selectedProvince && selectedProvince.province && selectedProvince.code &&
		regionData.some(e => e.province == selectedProvince.province && e.code == selectedProvince.code)
	) {
		// selectedProvince = selectedProvince;
	} else {
		selectedProvince = regionData[0];
	}
	activeProvinceItem(selectedProvince, 'isUserClick');
}

// 加载城市数据
function loadCities(province) {
	const cityCol = document.getElementById('cityCol');
	cityCol.innerHTML = '';

	province.cities.forEach((city, index) => {
		const item = document.createElement('div');
		item.className = 'picker-item';
		item.dataset.index = index;
		item.dataset.code = city.code;
		item.textContent = city.city;
		item.id = `C_${city.code}`;
		item.addEventListener('click', () => {
			activeCityItem(city, 'isUserClick');
		});
		cityCol.appendChild(item);
	});

	if (
		selectedCity && selectedCity.city && selectedCity.code &&
		selectedProvince.cities.some(e => e.city == selectedCity.city && e.code == selectedCity.code)
	) {
		// selectedCity = selectedCity;
	} else {
		selectedCity = selectedProvince.cities[0];
	}
	activeCityItem(selectedCity, 'isUserClick');
}

// 加载区县数据
function loadDistricts(city) {
	const districtCol = document.getElementById('districtCol');
	districtCol.innerHTML = '';

	city.areas.forEach((district, index) => {
		const item = document.createElement('div');
		item.className = 'picker-item';
		item.dataset.index = index;
		item.dataset.code = district.code;
		item.textContent = district.area;
		item.id = `D_${district.code}`;
		item.addEventListener('click', () => {
			activeDistrictItem(district, 'isUserClick');
		});
		districtCol.appendChild(item);
	});

	if (
		selectedDistrict && selectedDistrict.area && selectedDistrict.code &&
		selectedCity.areas.some(e => e.area == selectedDistrict.area && e.code == selectedDistrict.code)
	) {
		// selectedDistrict = selectedDistrict;
	} else {
		selectedDistrict = city.areas[0];
	}
	activeDistrictItem(selectedDistrict, 'isUserClick');
}

// 选中省份item
function activeProvinceItem(item, type) {
	const activeFn = throttle(function() {
		activeType = type;
		let animateTime = 0;
		if (activeType == 'isUserClick') {
			animateTime = 300;
		}
		if (activeType == 'isScroll') {
			animateTime = 0;
		}
		selectedProvince = item;
		const selectedId = `P_${selectedProvince.code}`;
		document.querySelectorAll('#provinceCol .picker-item').forEach(el => {
			el.classList.remove('active');
		});
		const itemCol = document.getElementById(selectedId);
		itemCol.classList.add('active');
		$("#provinceCol").animate({
			scrollTop: $(`#${selectedId}`).offset().top - $("#provinceCol").offset().top +
				$("#provinceCol").scrollTop() - 170
		}, animateTime);
		setTimeout(() => {
			activeType = "";
		}, animateTime);
	}, 300);
	activeFn();

	const loadFn = debounce(function() {
		loadCities(selectedProvince);
	}, 300);
	loadFn();
}

// 选中城市item
function activeCityItem(item, type) {
	const activeFn = throttle(function() {
		activeType = type;
		let animateTime = 0;
		if (activeType == 'isUserClick') {
			animateTime = 300;
		}
		if (activeType == 'isScroll') {
			animateTime = 0;
		}
		selectedCity = item;
		const selectedId = `C_${selectedCity.code}`;
		document.querySelectorAll('#cityCol .picker-item').forEach(el => {
			el.classList.remove('active');
		});
		const itemCol = document.getElementById(selectedId);
		itemCol.classList.add('active');
		$("#cityCol").animate({
			scrollTop: $(`#${selectedId}`).offset().top - $("#cityCol").offset().top +
				$("#cityCol").scrollTop() - 170
		}, animateTime);
		setTimeout(() => {
			activeType = "";
		}, animateTime);
	}, 300);
	activeFn();

	const loadFn = debounce(function() {
		loadDistricts(selectedCity);
	}, 300);
	loadFn();
}

// 选中区县item
function activeDistrictItem(item, type) {
	const activeFn = throttle(function() {
		activeType = type;
		let animateTime = 0;
		if (activeType == 'isUserClick') {
			animateTime = 300;
		}
		if (activeType == 'isScroll') {
			animateTime = 0;
		}
		selectedDistrict = item;
		const selectedId = `D_${selectedDistrict.code}`;
		document.querySelectorAll('#districtCol .picker-item').forEach(el => {
			el.classList.remove('active');
		});
		const itemCol = document.getElementById(selectedId);
		itemCol.classList.add('active');
		$("#districtCol").animate({
			scrollTop: $(`#${selectedId}`).offset().top - $("#districtCol").offset().top +
				$("#districtCol").scrollTop() - 170
		}, animateTime);
		setTimeout(() => {
			activeType = "";
		}, animateTime);
	}, 300);
	activeFn();

	const loadFn = debounce(function() {
		getPickerVal();
	}, 300);
	loadFn();
}

// 显示选择器
function showPicker() {
	pickerMask.classList.add('show');
	pickerContainer.classList.add('show');
	$("html").css("overscroll-behavior", "none");
	initPicker();
}

// 隐藏选择器
function hidePicker() {
	pickerMask.classList.remove('show');
	pickerContainer.classList.remove('show');
	$("html").css("overscroll-behavior", "auto");
	getPickerVal();
}

// 赋值
function getPickerVal() {
	const getFn = debounce(function() {
		if (selectedProvince && selectedCity && selectedDistrict) {
			cityPicker.value = `${selectedProvince.province} ${selectedCity.city} ${selectedDistrict.area}`;
			console.log(`Picker getPickerVal: ${selectBtn.textContent}`);
		}
	}, 300);
	getFn();
}

// ‌func‌：需要节流处理的函数。
// ‌delay‌：间隔时间（毫秒）。
// 间隔内均匀执行一次
function throttle(func, delay = 300) {
	let timer = null,
		lastTime = 0;
	return function(...args) {
		const now = Date.now();
		if (now - lastTime > delay) {
			clearTimeout(timer);
			func.apply(this, args);
			lastTime = now;
		} else if (!timer) {
			timer = setTimeout(() => {
				func.apply(this, args);
				lastTime = Date.now();
			}, delay);
		}
	};
}

// ‌func‌：需要防抖处理的函数。
// ‌wait‌：延迟时间（毫秒）。
// 停止触发后执行一次
function debounce(func, wait = 300) {
	let timer = null;
	return function(...args) {
		clearTimeout(timer);
		timer = setTimeout(() => {
			func.apply(this, args);
		}, wait);
	};
}